#include <iostream>
#include <sstream>
#include <jsoncpp/json/json.h>
#include <memory>

// json格式序列化
bool serialize(const Json::Value &val, std::string &jsonStr)
{
    // 实例化工厂类对象并生产派生类对象
    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    // 序列化
    std::stringstream ss;
    int ret = sw->write(val, &ss);
    if (ret != 0)
    {
        std::cout << "json serialize failed!\n";
        return false;
    }
    jsonStr = ss.str();
    return true;
}

// json格式反序列化
bool unSerialize(const std::string &jsonStr, Json::Value &val)
{
    // 实例化工厂类对象并生产派生类对象
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    // 反序列化
    std::string err;
    bool ret = cr->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.size(), &val, &err);
    if (ret == false)
    {
        std::cout << "json unserialize failed: " << err << std::endl;
        return false;
    }
    return true;
}

int main()
{
    // 测试序列化
    Json::Value person, fav;
    person["姓名"] = "zhangsan";
    person["年龄"] = 24;
    person["性别"] = "男";
    person["成绩"].append(90);
    person["成绩"].append(91);
    person["成绩"].append(92);
    fav["书籍"] = "挪威的森林";
    fav["电影"] = "豺狼的日子";
    person["爱好"] = fav;

    std::string jsonStr;
    serialize(person, jsonStr);
    std::cout << "serialize result: " << jsonStr << std::endl;

    // 测试反序列化
    Json::Value res;
    unSerialize(jsonStr, res);
    std::cout << "姓名：" << res["姓名"].asString() << std::endl;
    std::cout << "年龄：" << res["年龄"].asInt() << std::endl;
    std::cout << "性别：" << res["性别"].asString() << std::endl;
    int sz = res["成绩"].size();
    for(int i = 0; i < sz; i++)
        std::cout << "成绩：" << res["成绩"][i].asInt() << std::endl;
    std::cout << "爱好：书籍：" << res["爱好"]["书籍"].asString() << std::endl;
    std::cout << "爱好：电影：" << res["爱好"]["电影"].asString() << std::endl;
    return 0;
}